import asyncio
import argparse
from edge_tts import Communicate, list_voices

async def get_voices():
    """获取所有可用的语音"""
    voices = await list_voices()
    return [voice for voice in voices if 'zh-' in voice['Locale'].lower()]

async def text_to_speech(text, voice, output_file, rate="+0%", volume="+0%"):
    """将文本转换为语音"""
    communicate = Communicate(text, voice, rate=rate, volume=volume)
    await communicate.save(output_file)

def main():
    parser = argparse.ArgumentParser(description='Edge TTS 文本转语音工具')
    parser.add_argument('--text', '-t', type=str, help='要转换的文本')
    parser.add_argument('--file', '-f', type=str, help='从文件读取文本')
    parser.add_argument('--voice', '-v', type=str, default='zh-CN-XiaoxiaoNeural', 
                       help='语音名称')
    parser.add_argument('--output', '-o', type=str, default='output.mp3',
                       help='输出文件名')
    parser.add_argument('--rate', '-r', type=str, default='+0%',
                       help='语速调整 (-50% 到 +100%)')
    parser.add_argument('--volume', '-vol', type=str, default='+0%',
                       help='音量调整 (-100% 到 +100%)')
    parser.add_argument('--list-voices', '-l', action='store_true',
                       help='列出所有可用的中文语音')
    
    args = parser.parse_args()
    
    if args.list_voices:
        try:
            voices = asyncio.run(get_voices())
            print("可用的中文语音:")
            for voice in voices:
                print(f"{voice['ShortName']} - {voice['Locale']} - {voice['Gender']}")
        except Exception as e:
            print(f"获取语音列表失败: {e}")
        return
    
    # 读取文本
    text = ""
    if args.file:
        try:
            with open(args.file, 'r', encoding='utf-8') as f:
                text = f.read()
        except Exception as e:
            print(f"读取文件失败: {e}")
            return
    elif args.text:
        text = args.text
    else:
        parser.print_help()
        return
    
    if not text.strip():
        print("错误: 文本内容为空")
        return
    
    try:
        print(f"开始转换...")
        print(f"文本长度: {len(text)} 字符")
        print(f"使用语音: {args.voice}")
        print(f"输出文件: {args.output}")
        
        asyncio.run(text_to_speech(text, args.voice, args.output, args.rate, args.volume))
        print(f"转换完成！输出文件: {args.output}")
    except Exception as e:
        print(f"转换失败: {e}")

if __name__ == "__main__":
    main()